package com.example.zhilierp.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.zhilierp.entity.Permission;
import com.example.zhilierp.service.PermissionService;
import com.example.zhilierp.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 权限控制器
 * 处理权限相关的HTTP请求
 */
@RestController
@RequestMapping("/api/permission")
@Tag(name = "权限管理", description = "权限管理相关接口")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    /**
     * 分页查询权限列表
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param name 权限名称（可选）
     * @return 分页结果
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询权限列表", description = "根据条件分页查询权限列表")
    public Result<Page<Permission>> page(@RequestParam(defaultValue = "1") Integer pageNum,
                                      @RequestParam(defaultValue = "10") Integer pageSize,
                                      @RequestParam(required = false) String name) {
        try {
            Page<Permission> page = new Page<>(pageNum, pageSize);
            Page<Permission> resultPage = permissionService.page(page);
            return Result.success(resultPage);
        } catch (Exception e) {
            return Result.error(500, "查询权限列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询权限信息
     * @param id 权限ID
     * @return 权限信息
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询权限信息", description = "根据权限ID获取详细信息")
    public Result<Permission> getById(@PathVariable Long id) {
        try {
            if (id == null) {
                return Result.error(400, "权限ID不能为空");
            }
            Permission permission = permissionService.getById(id);
            if (permission == null) {
                return Result.error(404, "权限不存在");
            }
            return Result.success(permission);
        } catch (Exception e) {
            return Result.error(500, "查询权限信息失败: " + e.getMessage());
        }
    }

    /**
     * 新增权限
     * @param permission 权限信息
     * @return 操作结果
     */
    @PostMapping
    @Operation(summary = "新增权限", description = "创建新权限")
    public Result<Boolean> save(@RequestBody Permission permission) {
        try {
            if (permission == null) {
                return Result.error(400, "权限信息不能为空");
            }
            boolean success = permissionService.save(permission);
            return success ? Result.success(true) : Result.error(500, "新增权限失败");
        } catch (Exception e) {
            return Result.error(500, "新增权限失败: " + e.getMessage());
        }
    }

    /**
     * 修改权限
     * @param permission 权限信息
     * @return 操作结果
     */
    @PutMapping
    @Operation(summary = "修改权限", description = "更新权限信息")
    public Result<Boolean> update(@RequestBody Permission permission) {
        try {
            if (permission == null || permission.getId() == null) {
                return Result.error(400, "权限ID不能为空");
            }
            // 检查权限是否存在
            if (permissionService.getById(permission.getId()) == null) {
                return Result.error(404, "权限不存在");
            }
            boolean success = permissionService.updateById(permission);
            return success ? Result.success(true) : Result.error(500, "修改权限失败");
        } catch (Exception e) {
            return Result.error(500, "修改权限失败: " + e.getMessage());
        }
    }

    /**
     * 删除权限
     * @param id 权限ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除权限", description = "根据权限ID删除权限")
    public Result<Boolean> delete(@PathVariable Long id) {
        try {
            if (id == null) {
                return Result.error(400, "权限ID不能为空");
            }
            // 检查权限是否存在
            if (permissionService.getById(id) == null) {
                return Result.error(404, "权限不存在");
            }
            boolean success = permissionService.removeById(id);
            return success ? Result.success(true) : Result.error(500, "删除权限失败");
        } catch (Exception e) {
            return Result.error(500, "删除权限失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除权限
     * @param ids 权限ID数组
     * @return 操作结果
     */
    @DeleteMapping("/batch")
    @Operation(summary = "批量删除权限", description = "批量删除多个权限")
    public Result<Boolean> deleteBatch(@RequestBody Long[] ids) {
        try {
            if (ids == null || ids.length == 0) {
                return Result.error(400, "权限ID数组不能为空");
            }
            boolean success = permissionService.removeBatchByIds(List.of(ids));
            return success ? Result.success(true) : Result.error(500, "批量删除权限失败");
        } catch (Exception e) {
            return Result.error(500, "批量删除权限失败: " + e.getMessage());
        }
    }

    /**
     * 获取权限树结构
     * @return 权限树
     */
    @GetMapping("/tree")
    @Operation(summary = "获取权限树结构", description = "获取系统所有权限的树状结构")
    public Result<List<Permission>> getPermissionTree() {
        try {
            List<Permission> permissionTree = permissionService.getPermissionTree();
            return Result.success(permissionTree);
        } catch (Exception e) {
            return Result.error(500, "获取权限树失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户的菜单树
     * @param userId 用户ID
     * @return 菜单树
     */
    @GetMapping("/userMenuTree/{userId}")
    @Operation(summary = "获取用户的菜单树", description = "获取指定用户的菜单树结构")
    public Result<List<Permission>> getUserMenuTree(@PathVariable Long userId) {
        try {
            if (userId == null) {
                return Result.error(400, "用户ID不能为空");
            }
            List<Permission> menuTree = permissionService.getUserMenuTree(userId);
            return Result.success(menuTree);
        } catch (Exception e) {
            return Result.error(500, "获取用户菜单树失败: " + e.getMessage());
        }
    }

    /**
     * 根据角色ID查询权限列表
     * @param roleId 角色ID
     * @return 权限列表
     */
    @GetMapping("/role/{roleId}")
    @Operation(summary = "根据角色ID查询权限列表", description = "获取指定角色的所有权限")
    public Result<List<Permission>> getPermissionsByRoleId(@PathVariable Long roleId) {
        try {
            if (roleId == null) {
                return Result.error(400, "角色ID不能为空");
            }
            List<Permission> permissions = permissionService.selectPermissionsByRoleId(roleId);
            return Result.success(permissions);
        } catch (Exception e) {
            return Result.error(500, "查询角色权限失败: " + e.getMessage());
        }
    }

    /**
     * 保存角色权限
     * @param roleId 角色ID
     * @param permissionIds 权限ID列表
     * @return 操作结果
     */
    @PostMapping("/role/save")
    @Operation(summary = "保存角色权限", description = "为角色分配权限")
    public Result<Boolean> saveRolePermissions(@RequestParam Long roleId, @RequestBody List<Long> permissionIds) {
        try {
            if (roleId == null) {
                return Result.error(400, "角色ID不能为空");
            }
            boolean success = permissionService.saveRolePermissions(roleId, permissionIds);
            return success ? Result.success(true) : Result.error(500, "保存角色权限失败");
        } catch (Exception e) {
            return Result.error(500, "保存角色权限失败: " + e.getMessage());
        }
    }
}